<template>
  <div class="booking-history-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon @click="handleBack" class="back-icon"><ArrowLeft /></el-icon>
        <span class="title">预约记录</span>
      </div>
    </div>

    <!-- 状态筛选 -->
    <div class="status-filter">
      <div class="filter-tabs">
        <div 
          v-for="status in statusOptions" 
          :key="status.value"
          :class="['filter-tab', { active: selectedStatus === status.value }]"
          @click="handleStatusChange(status.value)"
        >
          {{ status.label }}
        </div>
      </div>
    </div>

    <!-- 预约列表 -->
    <div class="booking-list">
      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>加载中...</span>
      </div>
      
      <div v-else-if="bookingList.length === 0" class="empty-state">
        <img src="@/assets/imgs/search_null_data.png" alt="暂无数据" class="empty-image" />
        <p class="empty-text">暂无预约记录</p>
      </div>
      
      <div v-else class="booking-items">
        <div 
          v-for="booking in bookingList" 
          :key="booking.id"
          class="booking-item"
          @click="handleBookingClick(booking)"
        >
          <div class="booking-header">
            <div class="service-info">
              <img :src="booking.serviceIcon" :alt="booking.serviceName" class="service-icon" />
              <div class="service-details">
                <h4 class="service-name">{{ booking.serviceName }}</h4>
                <p class="service-type">{{ getServiceTypeText(booking.serviceType) }}</p>
              </div>
            </div>
            <div class="booking-status" :class="getStatusClass(booking.status)">
              {{ booking.status }}
            </div>
          </div>
          
          <div class="booking-content">
            <div class="booking-detail">
              <div class="detail-row">
                <span class="label">预约时间：</span>
                <span class="value">{{ booking.appointmentDate }} {{ booking.appointmentTime }}</span>
              </div>
              <div class="detail-row">
                <span class="label">服务地址：</span>
                <span class="value">{{ booking.address }}</span>
              </div>
              <div class="detail-row">
                <span class="label">联系人：</span>
                <span class="value">{{ booking.contactName }} {{ booking.contactPhone }}</span>
              </div>
              <div v-if="booking.specialRequirements" class="detail-row">
                <span class="label">特殊要求：</span>
                <span class="value">{{ booking.specialRequirements }}</span>
              </div>
            </div>
            
            <div class="booking-footer">
              <div class="price-info">
                <span class="original-price">{{ booking.originalPrice }}</span>
                <span class="current-price">{{ booking.priceAfterDiscounts }}</span>
              </div>
              <div class="booking-actions">
                <el-button 
                  v-if="booking.status === '待确认'"
                  size="small" 
                  type="danger" 
                  @click.stop="handleCancelBooking(booking.id)"
                >
                  取消预约
                </el-button>
                <el-button 
                  size="small" 
                  type="primary" 
                  @click.stop="handleViewDetail(booking)"
                >
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 预约详情弹窗 -->
    <el-dialog
      v-model="detailModalVisible"
      title="预约详情"
      width="90%"
      :before-close="handleCloseDetail"
    >
      <div v-if="selectedBooking" class="booking-detail-modal">
        <div class="detail-section">
          <h4>服务信息</h4>
          <div class="service-info-detail">
            <img :src="selectedBooking.serviceImg" :alt="selectedBooking.serviceName" class="service-image" />
            <div class="service-text">
              <h5>{{ selectedBooking.serviceName }}</h5>
              <p>{{ selectedBooking.serviceDescription }}</p>
            </div>
          </div>
        </div>
        
        <div class="detail-section">
          <h4>预约信息</h4>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">预约时间：</span>
              <span class="value">{{ selectedBooking.appointmentDate }} {{ selectedBooking.appointmentTime }}</span>
            </div>
            <div class="info-item">
              <span class="label">服务地址：</span>
              <span class="value">{{ selectedBooking.address }}</span>
            </div>
            <div class="info-item">
              <span class="label">联系人：</span>
              <span class="value">{{ selectedBooking.contactName }}</span>
            </div>
            <div class="info-item">
              <span class="label">联系电话：</span>
              <span class="value">{{ selectedBooking.contactPhone }}</span>
            </div>
            <div class="info-item">
              <span class="label">预约状态：</span>
              <span class="value status" :class="getStatusClass(selectedBooking.status)">{{ selectedBooking.status }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间：</span>
              <span class="value">{{ formatDateTime(selectedBooking.createdAt) }}</span>
            </div>
          </div>
        </div>
        
        <div v-if="selectedBooking.specialRequirements" class="detail-section">
          <h4>特殊要求</h4>
          <p class="special-requirements">{{ selectedBooking.specialRequirements }}</p>
        </div>
        
        <div class="detail-section">
          <h4>价格信息</h4>
          <div class="price-detail">
            <div class="price-row">
              <span>原价：</span>
              <span class="original-price">{{ selectedBooking.originalPrice }}</span>
            </div>
            <div class="price-row">
              <span>优惠价：</span>
              <span class="current-price">{{ selectedBooking.priceAfterDiscounts }}</span>
            </div>
            <div class="price-row total">
              <span>总价：</span>
              <span class="total-price">¥{{ selectedBooking.totalPrice }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseDetail">关闭</el-button>
          <el-button 
            v-if="selectedBooking && selectedBooking.status === '待确认'"
            type="danger" 
            @click="handleCancelBooking(selectedBooking.id)"
          >
            取消预约
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Loading } from '@element-plus/icons-vue'
import { 
  getServiceBookingHistoryApi, 
  getServiceBookingListApi, 
  cancelServiceBookingApi 
} from '@/api/service'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const bookingList = ref([])
const selectedStatus = ref('')
const detailModalVisible = ref(false)
const selectedBooking = ref(null)

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '待确认', value: '待确认' },
  { label: '已确认', value: '已确认' },
  { label: '已完成', value: '已完成' },
  { label: '已取消', value: '已取消' }
]

// 获取预约列表
const getBookingList = async () => {
  try {
    loading.value = true
    let response
    
    console.log('开始获取预约列表，状态筛选:', selectedStatus.value)
    
    if (selectedStatus.value) {
      response = await getServiceBookingListApi(selectedStatus.value)
    } else {
      response = await getServiceBookingHistoryApi()
    }
    
    console.log('预约历史响应:', response)
    console.log('响应码:', response?.code)
    console.log('响应消息:', response?.message)
    console.log('响应数据:', response?.data)
    
    // 处理不同的响应格式
    if (response && (response.code === 0 || response.code === 200)) {
      bookingList.value = response.data || []
      console.log('预约列表数据:', bookingList.value)
    } else {
      console.error('获取预约列表失败，响应:', response)
      ElMessage.error(response?.message || '获取预约列表失败')
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error(error.message || '获取预约列表失败')
  } finally {
    loading.value = false
  }
}

// 状态筛选
const handleStatusChange = (status) => {
  selectedStatus.value = status
  getBookingList()
}

// 预约点击
const handleBookingClick = (booking) => {
  selectedBooking.value = booking
  detailModalVisible.value = true
}

// 查看详情
const handleViewDetail = (booking) => {
  selectedBooking.value = booking
  detailModalVisible.value = true
}

// 关闭详情弹窗
const handleCloseDetail = () => {
  detailModalVisible.value = false
  selectedBooking.value = null
}

// 取消预约
const handleCancelBooking = async (bookingId) => {
  try {
    await ElMessageBox.confirm('确定要取消这个预约吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await cancelServiceBookingApi(bookingId)
    console.log('取消预约响应:', response)
    if (response && (response.code === 0 || response.code === 200)) {
      ElMessage.success('取消预约成功')
      getBookingList() // 刷新列表
      handleCloseDetail() // 关闭详情弹窗
    } else {
      ElMessage.error(response?.message || '取消预约失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消预约失败:', error)
      ElMessage.error(error.message || '取消预约失败')
    }
  }
}

// 返回上一页
const handleBack = () => {
  router.back()
}

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    '待确认': 'status-pending',
    '已确认': 'status-confirmed',
    '已完成': 'status-completed',
    '已取消': 'status-cancelled'
  }
  return statusMap[status] || 'status-default'
}

// 获取服务类型文本
const getServiceTypeText = (serviceType) => {
  const typeMap = {
    'home_service': '家庭服务',
    'cleaning_service': '清洁服务',
    'vip_service': 'VIP服务'
  }
  return typeMap[serviceType] || '其他服务'
}

// 格式化时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 测试API连接
// const testApiConnection = async () => {
//   try {
//     console.log('测试API连接...')
//     const response = await getServiceBookingHistoryApi()
//     console.log('API连接测试成功:', response)
//     ElMessage.success('API连接正常')
//   } catch (error) {
//     console.error('API连接测试失败:', error)
//     ElMessage.error('API连接失败: ' + error.message)
//   }
// }

onMounted(() => {
  getBookingList()
})
</script>

<style scoped>
.booking-history-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  background-color: #fff;
  padding: 12px 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-icon {
  font-size: 20px;
  cursor: pointer;
}

.title {
  font-size: 18px;
  font-weight: 600;
}

.status-filter {
  background-color: #fff;
  padding: 16px;
  margin-bottom: 8px;
}

/* .debug-actions {
  margin-top: 12px;
  display: flex;
  gap: 8px;
  justify-content: center;
} */

.filter-tabs {
  display: flex;
  gap: 8px;
}

.filter-tab {
  padding: 8px 16px;
  border-radius: 20px;
  background-color: #f0f0f0;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
}

.filter-tab.active {
  background-color: #409eff;
  color: #fff;
}

.booking-list {
  padding: 0 16px 20px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #666;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.empty-image {
  width: 120px;
  height: 120px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  color: #999;
  font-size: 14px;
}

.booking-items {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.booking-item {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
}

.booking-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

.booking-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.service-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.service-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  object-fit: cover;
}

.service-details {
  flex: 1;
}

.service-name {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 4px 0;
  color: #333;
}

.service-type {
  font-size: 12px;
  color: #666;
  margin: 0;
}

.booking-status {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-confirmed {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-completed {
  background-color: #d4edda;
  color: #155724;
}

.status-cancelled {
  background-color: #f8d7da;
  color: #721c24;
}

.booking-content {
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
}

.booking-detail {
  margin-bottom: 12px;
}

.detail-row {
  display: flex;
  margin-bottom: 6px;
  font-size: 14px;
}

.detail-row .label {
  color: #666;
  min-width: 80px;
}

.detail-row .value {
  color: #333;
  flex: 1;
}

.booking-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.original-price {
  font-size: 12px;
  color: #999;
  text-decoration: line-through;
}

.current-price {
  font-size: 16px;
  font-weight: 600;
  color: #e74c3c;
}

.booking-actions {
  display: flex;
  gap: 8px;
}

/* 详情弹窗样式 */
.booking-detail-modal {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 12px 0;
  color: #333;
  border-bottom: 2px solid #409eff;
  padding-bottom: 4px;
}

.service-info-detail {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.service-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  flex-shrink: 0;
}

.service-text h5 {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #333;
}

.service-text p {
  font-size: 14px;
  color: #666;
  margin: 0;
  line-height: 1.5;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-item .label {
  font-size: 12px;
  color: #666;
}

.info-item .value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.info-item .value.status {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 8px;
  font-size: 12px;
  width: fit-content;
}

.special-requirements {
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin: 0;
}

.price-detail {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
}

.price-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.price-row.total {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #e0e0e0;
  font-weight: 600;
}

.total-price {
  color: #e74c3c;
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .booking-footer {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .booking-actions {
    justify-content: center;
  }
}
</style>
